package moco.blatt5.mytakephoto;

import java.util.Calendar;

import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {
	private Uri captureImageUri;
	private final int CAPTURE_IMAGE = 1;
	private static final int START_CAM_AGAIN = 2;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.activity_main);
        
        takePicture(CAPTURE_IMAGE);
        
    }
	
	

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


	private void takePicture(int requestCode) {
		StorageHelper helper = new StorageHelper(this);
		if (helper.isExternalStorageAvailable() && helper.isExternalStorageWriteable()) {
			String filename = new DateFormat().format("yyyyMMdd-hhmmss", Calendar.getInstance().getTime()) + ".jpg";
			captureImageUri = helper.createImageDestinationUri(null, filename);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, captureImageUri);
			startActivityForResult(intent, requestCode);
		}
	}
	
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_CANCELED) {
			switch (requestCode) {
				case CAPTURE_IMAGE:
					storeLocally(captureImageUri);
					break;
			}
		} else if(requestCode == START_CAM_AGAIN) {
				takePicture(requestCode);
		}
	}
	
	private void storeLocally(Uri captureImageUri) {
		MediaScannerConnection.scanFile(this, new String[] { captureImageUri.getPath() }, null,	new MediaScannerConnection.OnScanCompletedListener() {
			public void onScanCompleted(String path, Uri uri) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(uri);
				
				startActivityForResult(intent, 2);
			}
		});
	}


} 












